package com.dzt.cloudreader.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.dzt.cloudreader.utils.ActivityStackManager;
import com.dzt.cloudreader.utils.JPreferenceKit;
import com.dzt.cloudreader.utils.JToastKit;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by M02323 on 2017/12/14.
 * 本类不涉及UI部分
 */

public abstract class SuperActivity extends AppCompatActivity {
	protected Context context;
	protected Bundle savedInstanceState;
	protected JPreferenceKit preferenceKit;
	//该对象作为subscription的容器，方便统一取消订阅
	private CompositeSubscription mCompositeSubscription;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.savedInstanceState = savedInstanceState;
		context = this;
		ActivityStackManager.getInstance().pushActivity(this);
		preferenceKit = JPreferenceKit.getInstance();
	}

	public void addSubscription(Subscription s) {
		if (mCompositeSubscription == null) {
			mCompositeSubscription = new CompositeSubscription();
		}
		mCompositeSubscription.add(s);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityStackManager.getInstance().popActivity(this);
		JToastKit.getInstance().cancelCurrentToast();
		if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
			mCompositeSubscription.unsubscribe();
		}
	}

	protected void showToast(String msg) {
		JToastKit.getInstance().showMessage(msg);
	}

	protected void showToast(int resId) {
		JToastKit.getInstance().showMessage(resId);
	}

	protected void startActivity(Class<?> cls, Intent intent) {
		if (intent == null) {
			intent = new Intent(context, cls);
		} else {
			intent.setClass(context, cls);
		}
		startActivity(intent);
	}

	protected void startActivityForResult(Class<?> cls, Intent intent, int requestCode) {
		if (intent == null) {
			intent = new Intent(context, cls);
		} else {
			intent.setClass(context, cls);
		}
		startActivityForResult(intent, requestCode);
	}
}
